package com.xzlf.config;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobTypeConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.api.strategy.impl.AverageAllocationJobShardingStrategy;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.xzlf.job.SimpleJobDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 作业三级配置：Core——Type——Lite
 */
@Configuration
public class ElasticJobConfig {

    @Value("${wuzzJob.cron}")
    private String cron;

    @Value("${wuzzJob.shardingTotalCount}")
    private int shardingTotalCount;

    @Value("${wuzzJob.shardingItemParameters}")
    private String shardingItemParameters;

    @Autowired
    private SimpleJobDemo simpleJobDemo;

    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    @Autowired
    private JobEventConfiguration jobEventConfig;

    @Bean(initMethod = "init")
    public JobScheduler simpleJobSchecduler(){
        //参数依次是 自定义任务类型实现类、cron表达式、分片数、分片参数
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration
                .newBuilder(
                        simpleJobDemo.getClass().getCanonicalName(),
                        cron,
                        shardingTotalCount
                )
                .shardingItemParameters(shardingItemParameters)
                .failover(true)
                .build();
        // 作业分片策略
        // 基于平均分配算法的分片策略
        String jobShardingStrategyClass  = AverageAllocationJobShardingStrategy.class.getName();

        JobTypeConfiguration jobTypeConfiguration =
                new SimpleJobConfiguration(jobCoreConfiguration, SimpleJobDemo.class.getCanonicalName());

        LiteJobConfiguration liteJobConfiguration =
                LiteJobConfiguration.newBuilder(jobTypeConfiguration)
                        .jobShardingStrategyClass(jobShardingStrategyClass)
                .overwrite(true)
                .build();

       return new SpringJobScheduler(simpleJobDemo, zookeeperRegistryCenter, liteJobConfiguration, jobEventConfig);
//        return new SpringJobScheduler(simpleJobDemo, zookeeperRegistryCenter, liteJobConfiguration);
    }
}
